package com.example.strategy;

import HslCommunication.Profinet.Siemens.SiemensS7Net;
import com.example.constant.OpcConstant;
import com.example.entity.DbBlock;
import com.example.exception.OpcException;
import com.example.s7.PlcSectionTwoConnectorFactory;

/**
 * Copyright: Copyright (c) 2022
 *
 * <p>
 * Description:
 *
 * @author LiuFeng
 * @version 2022/11/14 9:17
 * @since
 */
public interface PLCDataConvertStrategy {
    String convert(DbBlock dbBlock);

    String getType();

    /**
     * 从plc对象连接池中获取连接plc的对象
     *
     * @return 返回连接
     * @throws Exception 异常
     */
    default SiemensS7Net getConnect() throws Exception {
        return PlcSectionTwoConnectorFactory.borrowObject();
    }

    /**
     * 将获取的plc连接对象还给对象连接池
     *
     * @param siemensS7Net 连接plc的对象
     */
    default void returnConnect(SiemensS7Net siemensS7Net) {
        try {
            PlcSectionTwoConnectorFactory.returnObject(siemensS7Net);
        } catch (Exception e) {
            throw new OpcException(e);
        }
    }

    default String handleGroup(DbBlock dbBlock) {
        if (dbBlock.getCGroup() == null)
            return dbBlock.getCGroup();
        return dbBlock.getCGroup().replaceAll("[a-zA-Z]", "");
    }

    /**
     * 处理offset值
     *
     * @param dbBlock 数据块
     * @return offset值
     */
    default String handleOffset(DbBlock dbBlock) {
        String addrParams = dbBlock.getAddrParams();
        String address = null;
        String offset;
        if (addrParams.contains(",")) {
            String[] split = addrParams.split(",");
            address = split[0];
            offset = split[1];
        } else {
            offset = addrParams;
        }
        offset = offset.replaceAll("[a-zA-Z]", "");

//        if (offset.contains(".")) {
//            offset = offset.split("\\.")[0];
//        }
        offset = offset.replaceAll("\\.", "");

        return address+ OpcConstant.PERIOD +offset;
    }

    default void clearBuffer(StringBuffer buffer) {
        buffer.delete(0, buffer.length());
    }
}
